import defaultSettings from '@/settings';
import { useDynamicTitle } from '@/utils/dynamicTitle';
import { defineStore } from 'pinia';

const SETTINGS = [
  'sideTheme',
  'showBreadCrumb',
  'tagsView',
  'fixedHeader',
  'sidebarLogo',
  'dynamicTitle',
];
const storageSetting = JSON.parse(localStorage.getItem('layout-setting')) || {};

/**
 * 更新本地存储的系统设置
 * @param {string} prop 属性名称
 * @param {*} value 属性值
 */
function updateStorageSettings(prop, value) {
  if (!prop) return;
  const layoutSetting = localStorage.getItem('layout-setting');
  const setting = layoutSetting ? JSON.parse(layoutSetting) : {};
  setting[prop] = value;
  localStorage.setItem('layout-setting', JSON.stringify(setting));
}

/**
 * 初始化state值
 * @returns {Object} 可配置项对象
 */
function initState() {
  const state = {};
  SETTINGS.forEach(key => {
    state[key] = storageSetting[key] ?? defaultSettings[key];
  });
  return state;
}

const useSettingsStore = defineStore('settings', {
  state: () => ({
    title: '',
    ...initState(),
  }),
  actions: {
    // 修改布局设置
    changeSetting(data) {
      const { key, value } = data;
      if (this.hasOwnProperty(key)) {
        this[key] = value;
        updateStorageSettings(key, value);
      }
    },
    // 设置网页标题
    setTitle(title) {
      this.title = title;
      useDynamicTitle();
    },
    resetSetting() {
      for (let key in defaultSettings) {
        if (this.hasOwnProperty(key)) {
          this[key] = defaultSettings[key];
        }
      }
      localStorage.removeItem('layout-setting');
    },
  },
});

export default useSettingsStore;
